import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import { Cookies } from "react-cookie";
import enUS from "./locales/en-US.json";
import zhCN from "./locales/zh-CN.json";
import { LANGUAGE } from "@/constants/cookies";

export const defaultLanguage = "en-US";
const resources = {
  "en-US": { translation: enUS },
  "zh-CN": { translation: zhCN },
};

// 使用 react-cookie 来获取默认语言
const cookies = new Cookies();
const getLanguageFromCookie = (): string => {
  const cookieValue = cookies.get(LANGUAGE);
  return cookieValue || defaultLanguage;
};

const initialLanguage = getLanguageFromCookie();

i18n.use(initReactI18next).init({
  resources,
  lng: initialLanguage,
  fallbackLng: defaultLanguage,
  interpolation: {
    escapeValue: false, // react already safes from xss
  },
  // debug: process.env.NODE_ENV !== "production",
});

// 添加初始化完成检查
i18n.on("initialized", () => {
  console.log("i18n initialized successfully");
  console.log("Available languages:", i18n.languages);
  console.log("Current language:", i18n.language);
  console.log('Translation for "Profile":', i18n.t("Profile"));
});

export default i18n;
